// asy_server.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
using namespace boost::asio;
using namespace boost;

class server
{
private:
  io_service &ios;
  ip::tcp::acceptor acceptor;
  typedef shared_ptr<ip::tcp::socket> sock_pt;
public:
  server(io_service& io) : ios(io), acceptor(ios, ip::tcp::endpoint(ip::tcp::v4(), 6688))
  {
    start();
  }

  void start()
  {
    sock_pt sock(new ip::tcp::socket(ios));

    acceptor.async_accept(*sock, bind(&server::accept_handler, this, placeholders::error, sock));
  }

  void accept_handler(const system::error_code& ec, sock_pt sock)
  {
    if(ec)
      return;

    cout << "client:";
    cout << sock->remote_endpoint().address() << endl;
    sock->async_write_some(buffer(" zdhuang..."), bind(&server::write_handler, this, placeholders::error));

    start();
  }

  void write_handler(const system::error_code&)
  {
    cout << "send msg complete." << endl;
  }
};


int _tmain(int argc, _TCHAR* argv[])
{
  try
  {
    cout << "server start." << endl;
    io_service ios;
    server serv(ios);
    ios.run();
  }
  catch(...)
  {

  }
 
	return 0;
}